#include "app.h"
extern int port;
extern char* newbuffer;
extern int vedio_real_len;
extern pthread_mutex_t mutex;
void*sendvedio_to_app(void*arg)
{

    //创建udp向app发送视频数据
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
     {
        printf("sockfd error\n");
        exit(1);

     }
     struct sockaddr_in server;
     server.sin_family=AF_INET;
     server.sin_port=htons(port);
     server.sin_addr.s_addr=inet_addr("0.0.0.0");
     socklen_t len=sizeof(server);
     if(bind(sockfd,(const struct sockaddr*)&server,len)<0)//绑定
     {
         printf("bind error\n");
         exit(1);

     }
     struct sockaddr_in app_client;
     socklen_t le=sizeof(app_client);
     //app随便给服务器发送一个消息，服务器来接收，获得app的struct sockaddr_in
     char*buffer=(char*)malloc(VEDIOLEN);
     if(recvfrom(sockfd,buffer,5,0,(struct sockaddr*)&app_client,&le)<0)//接收一个hello为了获得app的struct sockaddr_in
     {
  
      printf("recvfrom error\n");
      exit(1);
  
  
     }
    
     //将app信息保存在了app_client中

    while(1) //获取视频数据发送到app
     {
        pthread_mutex_lock(&mutex);//加锁
        memset(buffer,0,VEDIOLEN);//buffer作为发送缓冲区
        memcpy(buffer,newbuffer,vedio_real_len);//将视频数据拷贝到发送缓冲区
        pthread_mutex_unlock(&mutex);//解锁
        //通过udp发送到app
        if(sendto(sockfd,buffer,vedio_real_len,0,(const struct sockaddr*)&app_client,le)<0)//第五个参数保存app客户端的信息
        {
            printf("sendto\n");
            exit(1);
        }
          usleep(30000);//发送慢一点
     }


}
void deal_vedio_to_app(int fd)//fd为app
{  
   //2.需要给app返回端口号port使用json   {"cmd":"return_port","port":9001};
    struct json_object*obj=json_object_new_object();
    json_object_object_add(obj,"cmd",json_object_new_string("return_port"));
    json_object_object_add(obj,"port",json_object_new_int(port));
    const char*ptr=json_object_to_json_string(obj);//将json_object转化为char*

    //3.使用tcp返回给app,端口号信息，方便app建立udp接收服务器的视频数据
    if(send(fd,ptr,strlen(ptr),0)<0)
    {
        printf("send error\n");
        exit(1);
     

    }
   pthread_t tid;
   pthread_create(&tid,NULL,sendvedio_to_app,NULL);//创建线程去完成视频发送到app,主线程一直accept处理客户端连接


}
void send_control(struct json_object*obj)
{
   
    struct json_object*val;
    json_object_object_get_ex(obj,"deviceid",&val);//获取deviceid
    const char*deviceid=json_object_get_string(val);//将deviceid转化为字符串
    const char*buf=json_object_to_json_string(obj);//将{"cmd":"control","action":"left","appid":"1000","deviceid":"0001"}
                                                   //准备发送给板子
    
    int fd=findlist(deviceid);//根据解析到的摄像头deviceid号找到网络fd
    if(fd<0)
    {

     printf("摄像头不存在\n");


    }
    else
    {
       if(send(fd,buf,strlen(buf),0)<0)//使用tcp 发送给板子
       {  
            printf("服务器转发控制信号失败\n");
   
       }



    }






}